#include "cache_server.hpp"
#include "WriteRead.hpp"
#include "HeartBeat.hpp"
void *heart_beat(void *arg){
    Heartbeat heartbeat_hd((struct heartbeat_struct *)arg);
    heartbeat_hd.heartbeat_connect();
    while(1){
        heartbeat_hd.heartbeat_send();
        Sleep_ms(100);
        int commond = heartbeat_hd.is_anycommond();
        if(SHUTDOWN_CACHE==commond){
            pthread_rwlock_wrlock(&ipchange_lock);
            heartbeat_hd.shutdown_handler();
            pthread_rwlock_unlock(&ipchange_lock);
            break;
        }
        else if(ADD_CACHE==commond){
            pthread_rwlock_wrlock(&ipchange_lock);
            heartbeat_hd.add_handler();
            pthread_rwlock_unlock(&ipchange_lock);
        }
        else if(REFLESH_IP==commond){
            pthread_rwlock_wrlock(&ipchange_lock);
            heartbeat_hd.reflesh_handler();
            pthread_rwlock_unlock(&ipchange_lock);
        }
    }
    return nullptr;
}

int main(){
    ConsistentHash key_addr(100);
    std::vector<std::string> ipport_list;
    LRUCache LC(100);
    ThreadPool ThrPl(10,20);
    pthread_t tid_heartbeat;
    struct heartbeat_struct heartbeat_arg;
    heartbeat_arg.ThrPl = &ThrPl;
    heartbeat_arg.LC = &LC;
    heartbeat_arg.key_addr = &key_addr;
    heartbeat_arg.ipport_list = &ipport_list;
    Pthread_create(&tid_heartbeat, nullptr, heart_beat, &heartbeat_arg);  

    WriteRead WR_CACHE(&ThrPl, &LC);
    WR_CACHE.WR_listen();
    for(;;){
        int nready = WR_CACHE.WR_listenWait(500);
        if(nready<=0)
            continue;
        pthread_rwlock_rdlock(&ipchange_lock);
        for(int i=0;i<nready;i++){
            if(WR_CACHE.is_listenfd(i))
                WR_CACHE.WR_listenHandler();
            else
                WR_CACHE.WR_cfdHandler(i);
        }
        pthread_rwlock_unlock(&ipchange_lock);
    }
    return 0;
}

